package com.example;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/hellocookie")
public class HelloCookie extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // cookie 服务器从客户端读取的记录数据
        PrintWriter out = resp.getWriter();

        // 从request中获得cookie
        Cookie[] cookies = req.getCookies();
        if(cookies != null){
            out.write("你上一次访问:");
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if(cookie.getName().equals("lastLoginTime")){
                    long parseLong = Long.parseLong(cookie.getValue());
                    Date date = new Date(parseLong);
                    out.write(date.toString());
                }

            }
        }else{
            out.write("这是你第一次访问这个网站");
        }

        // 新建cookie
        // 一个cookie只能存一个字符串数据, 一个网站只能存20个cookie,浏览器最大300个cookie,每个cookie最大4k
        Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+"");
        // 设置cookie有效期(秒)
        // 未设置有效期,关闭浏览器即丢失
        cookie.setMaxAge(24*60*60);
        // 服务器向cookie存放字符串
        resp.addCookie(cookie);
        

    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
